package cn.edu.bzu.ie.sf.mealsmisweb.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;

/**
 * 上传文件的通用控制器类
 * @date 2019-03-23 17:30
 * @author : 宋锋
 * 参考地址：https://blog.csdn.net/h996666/article/details/86077499
 */
@RestController
@RequestMapping("/uploadFile")
public class UploadFile {
    // 文件实际存放路径
    private String rootFilePath = AppConstant.ROOT_FILE_PATH;     //取得文件的根路径

    //上传文件的方法
    @RequestMapping(value="/upload" , method = RequestMethod.POST)
    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException{
        long  startTime=System.currentTimeMillis();
        String filePath = AppConstant.FILE_PATH + request.getParameter("fileSavePath");
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        ServletContext servletContext = request.getSession().getServletContext();
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(servletContext);
        String savedFileName = "";   //保存后的文件名

        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null){
                    String fileRealName = file.getOriginalFilename();                   //获得原始文件名;
                    int pointIndex =  fileRealName.indexOf(".");                        //点号的位置
                    String fileSuffix = fileRealName.substring(pointIndex);             //截取文件后缀
                    UUID FileId = UUID.randomUUID();                        //生成文件的前缀包含连字符
                    savedFileName = FileId.toString().replace("-","").concat(fileSuffix);       //文件存取名

                    //String path="E:/springUpload"+file.getOriginalFilename();
                    //String path = servletContext.getRealPath("") + filePath + "/" + savedFileName;
                    String path = filePath + "/" + savedFileName;
                    System.out.println("文件路径："+path);

                    //上传
                    file.transferTo(new File(path));
                }
            }

        }
        //long  endTime=System.currentTimeMillis();
        //System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
        //return "/success";
        return savedFileName;
    }

    //上传文件的方法
    @RequestMapping(value="/delFile" , method = RequestMethod.POST)
    public boolean  delFile(String filePath) throws IllegalStateException, IOException{
        //String filePath = request.getParameter("filePath");
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        //String path = request.getSession().getServletContext().getRealPath("") + filePath;
        String path = AppConstant.FILE_PATH + filePath;
        File delFile = new File(path);   //要删除的文件

        boolean flag = false;   //删除标志，默认为false，不成功
        if(delFile.isFile() && delFile.exists()){
            delFile.delete();
            flag = true;
        }

        return flag;
    }
}
